package com.coze.lg.cozeagent.controller.oldtest;

import com.coze.lg.cozeagent.config.CozeConfig;
import com.coze.lg.cozeagent.controller.AipSpeech;
import com.coze.openapi.service.service.CozeAPI;
import com.sun.net.httpserver.HttpServer;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;

public class socketHttp extends Thread {
    private final int port;
    private final CozeAPI cozeAPI;
    // 初始化一个AipSpeech
    private final AipSpeech aipSpeech;

    public socketHttp(int port) {
        this.port = port;
        this.cozeAPI = new CozeConfig().cozeAPI();
        this.aipSpeech = new AipSpeech();
    }

    @Override
    public void run() {
        try {
            HttpServer server = HttpServer.create(new InetSocketAddress(port), 0);
            server.createContext("/pcm/post", exchange -> {
                String requestMethod = exchange.getRequestMethod();
                StringBuilder cacheContent = new StringBuilder();
                ByteArrayOutputStream cacheOutputStream = new ByteArrayOutputStream();
                if (requestMethod.equals("POST")) {
                    try (InputStream reqBodyStream = exchange.getRequestBody()) {
                        ((Runnable) () -> {
                            SessionHttp session = new SessionHttp(reqBodyStream, cacheOutputStream, aipSpeech, cozeAPI);
                            session.do_start();
                        }).run();
                        System.out.println("客户端已连接");
                    } catch(IOException e) {
                        System.out.println("处理http失败" + e.getMessage());
                    }
                } else {
                    System.out.println("<UNK>");
                }
                ByteArrayOutputStream outContent = new ByteArrayOutputStream();
                outContent.write("ok send".getBytes());
                exchange.sendResponseHeaders(200, outContent.size());
                exchange.getResponseBody().write(outContent.toByteArray());
            });
            server.start();
            System.out.println("等待客户端连接...");
        } catch (IOException e) {
            System.err.println("Socket错误: " + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("未预期的错误: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
